package com.epam.kulibaba.components.mainPage;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Reporter;

import com.epam.kulibaba.components.Component;
import com.epam.kulibaba.helpers.Class.Category;

public class ProductsContainer extends Component {
	public static final String CONTAINER = "//div[@class ='home-page-cloud']";
	@FindBy(xpath = ProductsContainer.CONTAINER)
	private  WebElement container;
	
	public WebElement getContainer(){
		return container;
	}	

	public  ProductsContainer getProductsContainer(WebDriver driver) {
		ProductsContainer productsContainer = PageFactory.initElements(driver,
				ProductsContainer.class);		
		return productsContainer;
	}
	
	public static List<Category> getCategoryListMain(ProductsContainer container) {
		List<Category> categories = new ArrayList<Category>();
		try {
			Category category = null;
			String name;
			List<WebElement> itemCategories = container.getContainer()
					.findElements(By.cssSelector("*"));
			for (WebElement element : itemCategories) {
				if (element.getTagName().toLowerCase().equalsIgnoreCase("a")) {
					name = element.getText();
					category = new Category(element, name);
					categories.add(category);					
				}				
			}
		} catch (Exception e) {
			System.out.println("structure was changed");
		}
		return categories;
	}

	public static Category findCategory(ProductsContainer container,
			String nameCategory) {				
		for (Category category : getCategoryListMain(container)) {			
			if (category.name.equalsIgnoreCase(nameCategory)) {
				return category;
			}
			for(Category subcategory : category.categories){
				if (subcategory.name.equalsIgnoreCase(nameCategory)) {
					return subcategory;
				}
			}
		}
		return null;
	}
	
	public static void goToCategory(ProductsContainer container,
			String nameCategory) {
		Reporter.log("Go to page Category - " + nameCategory);
		ProductsContainer.findCategory(container, nameCategory).click();
	}

}
